<template>
  <view class="invite-container">
    <z-paging ref="paging" v-model="userList" @query="queryList">
      <template #top>
        <!-- 顶部导航栏 -->
        <u-navbar :border="false" bg-color="#fff" title-color="#333" :safe-area-inset-top="true" placeholder>
          <template #left>
            <view class="navbar-left" @click="goBack">
              <u-icon name="arrow-left" size="20" color="#333"></u-icon>
            </view>
          </template>
          <template #center>
            <text class="navbar-title">{{ useT('我的邀请') }}</text>
          </template>
        </u-navbar>

        <!-- 收益展示区域 -->
        <view class="earnings-section">
          <view class="earnings-card">
            <view class="earnings-item">
              <text class="earnings-label">{{ useT('累计收益') }}</text>
              <text class="earnings-value">{{ earningsData.totalEarnings || '0.00' }} USDT</text>
            </view>
            <view class="earnings-divider"></view>
            <view class="earnings-item">
              <text class="earnings-label">{{ useT('昨日收益') }}</text>
              <text class="earnings-value">{{ earningsData.yesterdayEarnings || '0.00' }} USDT</text>
            </view>
          </view>
        </view>
      </template>

      <!-- 页面内容 -->
      <view class="content">
        <!-- 用户列表 -->
        <view class="user-list">
          <view class="user-item" v-for="(user, index) in userList" :key="user.uid || index">
            <view class="user-left">
              <view class="user-avatar">
                <image v-if="user.avatar" :src="user.avatar" mode="aspectFill" style="width: 100%; height: 100%; border-radius: 50%" />
                <text v-else class="avatar-text">{{ (user.nickname || user.phone || 'U').charAt(0) }}</text>
              </view>
            </view>
            <view class="user-right">
              <view class="user-info">
                <text class="user-name">{{ user.nickname || user.phone || useT('未设置昵称') }}</text>
                <text class="user-time">{{ formatTime(user.time) }}</text>
                <view class="user-commission" style="margin-top: 8rpx">
                  <text class="commission-label">{{ useT('下级人数') }}:</text>
                  <text class="commission-value">{{ user.childCount ?? 0 }}</text>
                </view>
                <view class="user-commission" style="margin-top: 6rpx">
                  <text class="commission-label">{{ useT('订单数') }}:</text>
                  <text class="commission-value">{{ user.orderCount ?? 0 }}</text>
                </view>
                <view class="user-commission" style="margin-top: 6rpx">
                  <text class="commission-label">{{ useT('邀请数') }}:</text>
                  <text class="commission-value">{{ user.numberCount ?? 0 }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>
  </view>
</template>

<script setup>
import { getInviteUserList } from '@/api/invite';
import { updateUserInfo } from '@/api/user';
import { useT } from '@/utils/i18n';
import { onMounted, ref } from 'vue';

// 响应式数据
const userList = ref([]);
const paging = ref(null);
const earningsData = ref({
  totalEarnings: '0.00',
  yesterdayEarnings: '0.00'
});

// z-paging 查询方法
const queryList = async (pageNum, pageSize) => {
  console.log(`加载第${pageNum}页，每页${pageSize}条数据`);

  try {
    const res = await getInviteUserList({
      page: pageNum,
      limit: pageSize
    });
    console.log('====>res', res.data.list);
    // 处理接口返回的数据
    if (res.data && Array.isArray(res.data.list)) {
      // 传入列表与总数，便于z-paging计算分页
      if (paging.value && typeof paging.value.completeByTotal === 'function' && typeof res.data.count === 'number') {
        paging.value.completeByTotal(res.data.list, res.data.count);
      } else {
        paging.value.complete(res.data.list);
      }
    } else {
      // 数据格式异常
      console.error('接口返回数据格式异常:', res);
      paging.value.complete([]);
    }
  } catch (error) {
    console.error('获取邀请用户列表失败:', error);
    // 请求失败，显示空数据
    paging.value.complete([]);
    // 可选：显示错误提示
    uni.showToast({
      title: useT('加载失败，请重试'),
      icon: 'none',
      duration: 2000
    });
  }
};

// 获取收益数据
const fetchEarnings = async () => {
  try {
    const res = await updateUserInfo();
    if (res.status === 200 && res.data) {
      earningsData.value = {
        totalEarnings: res.data.sum_usdt || '0.00',
        yesterdayEarnings: res.data.zuori_usdt || '0.00'
      };
    }
  } catch (error) {
    console.error('获取邀请收益失败:', error);
  }
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  // 接口已返回格式化后的字符串，如 "2025/11/11"
  if (typeof time === 'string') return time.replace(/-/g, '/');
  const date = new Date(time * 1000 || time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 生命周期
onMounted(() => {
  console.log('邀请页面加载完成');
  fetchEarnings();
});
</script>

<style lang="scss" scoped>
.invite-container {
  min-height: 100vh;
  background-color: #f8f9fa;
}

.navbar-left {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

// 收益展示区域
.earnings-section {
  padding: 24rpx;
  background-color: #f8f9fa;

  .earnings-card {
    display: flex;
    background-color: #ffffff;
    border-radius: 16rpx;
    padding: 32rpx 24rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

    .earnings-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;

      .earnings-label {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 12rpx;
      }

      .earnings-value {
        font-size: 36rpx;
        font-weight: 700;
        color: #12c284;
      }
    }

    .earnings-divider {
      width: 1rpx;
      background-color: #e5e5e5;
      margin: 0 24rpx;
    }
  }
}

.content {
  padding: 0rpx 24rpx;

  // 用户列表
  .user-list {
    .user-item {
      display: flex;
      background-color: #ffffff;
      border-radius: 16rpx;
      padding: 24rpx;
      margin-bottom: 16rpx;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.98);
      }

      .user-left {
        margin-right: 24rpx;

        .user-avatar {
          width: 96rpx;
          height: 96rpx;
          border-radius: 50%;
          background: linear-gradient(135deg, #12c284 0%, #0ea572 100%);
          display: flex;
          align-items: center;
          justify-content: center;

          .avatar-text {
            font-size: 32rpx;
            font-weight: 600;
            color: #ffffff;
          }
        }
      }

      .user-right {
        flex: 1;
        display: flex;
        align-items: flex-start;

        .user-info {
          flex: 1;
          display: flex;
          flex-direction: column;

          .user-name {
            display: block;
            font-size: 32rpx;
            font-weight: 600;
            color: #333;
            margin-bottom: 8rpx;
            line-height: 1.3;
          }

          .user-time {
            display: block;
            font-size: 24rpx;
            color: #999;
            margin-bottom: 12rpx;
            line-height: 1.2;
          }

          .user-commission {
            display: flex;
            align-items: center;

            .commission-label {
              font-size: 24rpx;
              color: #666;
              margin-right: 8rpx;
            }

            .commission-value {
              font-size: 28rpx;
              color: #12c284;
              font-weight: 600;
            }
          }
        }
      }
    }
  }
}
</style>
